import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

@Slf4j
public class NIOSelectorServiceDemo {

    @Test

    public void test() throws Exception {
        // 创建selector
        Selector selector = Selector.open();// 1-打开多路复用器
        // 创建通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();// 2-打开一个ServerSocketChannel通道
        serverSocketChannel = serverSocketChannel.bind(new InetSocketAddress(8888));// 3-绑定到8888端口
        serverSocketChannel.configureBlocking(false);        // 4-ServerSocketChannel通道设置为非阻塞
        // 注册通道到selector
        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);// 4-ServerSocketChannel通道注册到Selector多路复用器

        Set selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
        // 等到selector监听和分发事件
        while(keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            if(key.isAcceptable()) {
                // a connection was accepted by a ServerSocketChannel.
            } else if (key.isConnectable()) {
                // a connection was established with a remote server.
            } else if (key.isReadable()) {
                // a channel is ready for reading
            } else if (key.isWritable()) {
                // a channel is ready for writing
            }
            keyIterator.remove();
        }
    }
}